package com.asseco.mio.codex.controllers;

import com.asseco.mio.Assessments;
import com.asseco.mio.BasicInfo;
import com.asseco.mio.WorkPosition;
import com.asseco.mio.codex.AssMark;
import com.asseco.mio.codex.AssessmentsForm;
import com.asseco.mio.codex.DeleteReason;
import com.asseco.mio.codex.UnassessedReason;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.hibernate.Query;
import org.hibernate.Session;
import com.asseco.persistence.service.HibernateUtil;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;

@Controller
@RequestMapping("/assessmentform*")
public class AssessmentsFormController extends BaseFormController {

    private String bi1 = "";
    private GenericManager<Assessments, String> assessmentManager = null;
    private GenericManager<BasicInfo, String> basicInfoManager = null;
    private GenericManager<WorkPosition, String> workPositionManager = null;
    private GenericManager<UnassessedReason, String> unassessedReasonManager = null;
    private GenericManager<AssMark, String> assMarkManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    private GenericManager<DeleteReason, String> deleteReasonManager = null;

    public String getBi1() {
        return bi1;
    }

    public void setBi1(String bi1) {
        this.bi1 = bi1;
    }
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setAssessmentManager(@Qualifier("assessmentManager") GenericManager<Assessments, String> assessmentManager) {
        this.assessmentManager = assessmentManager;
    }

    @Autowired
    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
        this.basicInfoManager = basicInfoManager;
    }

    @Autowired
    public void setWorkPositionManager(@Qualifier("workPositionManager") GenericManager<WorkPosition, String> workPositionManager) {
        this.workPositionManager = workPositionManager;
    }

    @Autowired
    public void setUnassessedReasonManager(@Qualifier("unassessedReasonManager") GenericManager<UnassessedReason, String> unassessedReasonManager) {
        this.unassessedReasonManager = unassessedReasonManager;
    }

    @Autowired
    public void setAssMarkManager(@Qualifier("assMarkManager") GenericManager<AssMark, String> assMarkManager) {
        this.assMarkManager = assMarkManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

     @Autowired
    public void setDeleteReasonManager(GenericManager<DeleteReason, String> deleteReasonManager) {
        this.deleteReasonManager = deleteReasonManager;
    }

    public AssessmentsFormController() {
        setCancelView("redirect:searchAssessments");
        setSuccessView("redirect:searchAssessments");
    }

    @ModelAttribute
    public AssessmentsForm assessmentsForm(String bi) {
        if (bi == null) {
            if (bi1.equals("")) {
                AssessmentsForm x = new AssessmentsForm(new Assessments(), getAllActiveUnassessedReason(this.unassessedReasonManager.getAll()), getAllActiveAssMark(this.assMarkManager.getAll()));
                return x;
            } else {
                Assessments a = new Assessments();
                a.setWorkPosition(workPositionManager.get(bi1));
                AssessmentsForm x = new AssessmentsForm(a, getAllActiveUnassessedReason(this.unassessedReasonManager.getAll()), getAllActiveAssMark(this.assMarkManager.getAll()));
                return x;
            }
        }
        this.setBi1(bi);
        Assessments a = new Assessments();
        a.setWorkPosition(workPositionManager.get(bi1));
        AssessmentsForm x = new AssessmentsForm(a, getAllActiveUnassessedReason(this.unassessedReasonManager.getAll()), getAllActiveAssMark(this.assMarkManager.getAll()));

        return x;
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected AssessmentsForm showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String id = request.getParameter("id");
        String bi = request.getParameter("bi");
         String userString2 = request.getRemoteUser();
            if (userString2 != null) {
                FirstLoginCheck x = new FirstLoginCheck();

                if (x.isFirstLogin(userString2)) {
                    response.sendRedirect("/MIO/firstlogin");
                }
            }


        AssessmentsForm x = new AssessmentsForm(null, getAllActiveUnassessedReason(this.unassessedReasonManager.getAll()), getAllActiveAssMark(this.assMarkManager.getAll()), this.deleteReasonManager.getAll());
        if (!StringUtils.isBlank(id)) {
            x.setAssessment(assessmentManager.get(id));
            this.setBi1(x.getAssessment().getWorkPosition().getId());
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assesmentsform", "assesments.show", x.getAssessment().getWorkPosition().getEmployment().getLastName(),
                    request.getQueryString(), request.getRemoteHost(), new Date()));

        }
        if (!StringUtils.isBlank(bi)) {
            x = this.assessmentsForm(bi);
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assesmentsform", "assesments.show", x.getAssessment().getWorkPosition().getEmployment().getLastName(),
                    request.getQueryString(), request.getRemoteHost(), new Date()));

        }

        return x;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(AssessmentsForm assessmentsForm, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            this.setBi1("");
            assessmentsForm.setAssessment(null);
            return getCancelView();
        }
        if (validator != null) { // validator is null during testing
            // validator.validate(assessmentsForm, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "assessmentform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (assessmentsForm.getAssessment().getId().equals(""));
        String success = getSuccessView();
        Locale locale = request.getLocale();


          if (!assessmentsForm.getSavedReason().getId().equals("")) {


            DeleteReason delRes = deleteReasonManager.get(assessmentsForm.getSavedReason().getId());


            String info2 = delRes.toString();
            String info1 = assessmentsForm.getAssessment().toString();
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assesmentsform", "assesments.delete", info1,
                    info2, request.getRemoteHost(), new Date()));
            assessmentManager.remove(assessmentsForm.getAssessment().getId());
            saveMessage(request, getText("assessmentsForm.deleted", locale));
            this.setBi1("");
            assessmentsForm.setAssessment(null);
           success = "searchAssessments";
        } else {
            Assessments x = assessmentsForm.getAssessment();
            WorkPosition y = workPositionManager.get(assessmentsForm.getAssessment().getWorkPosition().getId());
            x.setWorkPosition(y);
            if (x.getIsAssessed() == true) {
                x.setUnassReason(null);
            }
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Query q = session.createQuery("from Assessments assess where ( "
                    + "assess.workPosition.employment.firstName like '" + x.getWorkPosition().getEmployment().getFirstName() + "' and "
                    + "assess.workPosition.employment.lastName like '" + x.getWorkPosition().getEmployment().getLastName() + "' and "
                    + "assess.workPosition.employment.socScrNo like '" + x.getWorkPosition().getEmployment().getSocScrNo() + "' and "
                    + "assess.assHalf like '" + x.getAssHalf() + "' and "
                    + "assess.assYear = '" + x.getAssYear() + "')");


            List tempResult = q.list();
            session.getTransaction().commit();

            if (tempResult.isEmpty()) {
                if(x.getIsAssessed()==false){
                    x.setAssmark(null);
                }
                else{
                    if(x.getAssmark()==null||x.getAssmark().getId().equals("")){
                        double doub = x.getAssessment();

                        session.beginTransaction();
                    Query qq = session.createQuery("from ASS_MARK assess where ( "
                    + "assess.numAssMarkFrom <= '" +doub+ "' and "
                    + "assess.numAssMarkTo >= '" + doub + "')");


            List tempResult1 = qq.list();
            List result = new ArrayList();
        for (int j = 0; j < tempResult1.size(); j++) {
            AssMark object = (AssMark) tempResult1.get(j);
            result.add(object);
        }
            x.setAssmark((AssMark)result.get(0));

                    }
                }
                assessmentManager.save(x);
                String key = (isNew) ? "assessmentsForm.added" : "assessmentsForm.updated";
                saveMessage(request, getText(key, locale));
                auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "assesmentsform", key, assessmentsForm.getAssessment().getWorkPosition().getEmployment().getLastName(),
                        "test", request.getRemoteHost(), new Date()));
                this.setBi1("");
                assessmentsForm.setAssessment(null);
                success = "searchAssessments";

            } else {
                if (assessmentsForm.getAssessment().getId().equals("")){
                     saveMessage(request, getText("assessmentsForm.ImaAssessmentZaIzbranataGodinaIPolugodie", locale));
                     this.setBi1("");
                     assessmentsForm.setAssessment(null);
                     success = "searchAssessments";
                }else{
                
               
                    assessmentManager.save(assessmentsForm.getAssessment());
                saveMessage(request, getText("assessmentsForm.updated", locale));
                this.setBi1("");
                assessmentsForm.setAssessment(null);
                 success = "searchAssessments";
                }
                
            }
        }



        return success;
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    public List getAllActiveUnassessedReason(List<UnassessedReason> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            UnassessedReason ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveAssMark(List<AssMark> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            AssMark ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}
